<?php
namespace Admin\Logic;
use Admin\Transformer\CustomerTransformer;
use Think\Model;
/**
 * Created by PhpStorm.
 * User: sunku
 * Date: 2017/12/19
 * Time: 13:49
 */
class CustomerLogic extends Model{
    protected $trueTableName = 'wz_customers';

    public function saveCustomer($params){
        $id = isset($params['id'])? intval($params['id']):0;
        $admin_id = isset($params['admin_id'])? trim($params['admin_id']):0;
        $name = isset($params['name'])? trim($params['name']):0;
        $cid = isset($params['cid'])? intval($params['cid']):0;
        $company_name = isset($params['company_name'])? trim($params['company_name']):0;
        $product_name = isset($params['product_name'])? trim($params['product_name']):0;
        $level = isset($params['level'])? intval($params['level']):1;
        $type = isset($params['type'])? intval($params['type']):0;
        $gender = isset($params['gender'])? intval($params['gender']):1;
        $mobile = isset($params['mobile'])? trim($params['mobile']):0;
        $tel = isset($params['tel'])? trim($params['tel']):0;
        $wechat = isset($params['wechat'])? trim($params['wechat']):0;
        $qq = isset($params['qq'])? trim($params['qq']):1;
        $status = isset($params['status'])? intval($params['status']):0;
        $second_cid = isset($params['second_cid'])? intval($params['second_cid']):0;


        if(!$name){
           return Response(2001,"请填写联系人");
        }
        if(!$company_name){
            return Response(2001,"请填写公司名称");
        }

        if(!$product_name){
            return Response(2001,"请填写推广产品名称");
        }
        if($mobile && !preg_match("/^1[34578]\d{9}$/",$mobile)){
            return Response(2001,"手机号不合法");
        }
        if($tel && !preg_match("/^0\d{2,3}-\d{7,8}$/",$tel)){
            return Response(2001,"固话不合法");
        }
        $userInfo = D('Resource/User','Service')->getUserInfo(['id'=>$admin_id]);
        $data = [];
        $name && $data['name'] = $name;
        $cid && $data['cid'] = $cid;
        $status && $data['status'] = $status;

        $company_name && $data['company_name'] = $company_name;
        $product_name && $data['product_name'] = $product_name;
        $level && $data['level'] = $level;
        $type && $data['type'] = $type;
        $gender && $data['gender'] = $gender;
        $mobile && $data['mobile'] = $mobile;
        $wechat && $data['wechat'] = $wechat;
        $qq && $data['qq'] = $qq;
        $tel && $data['tel'] = $tel;
        $tel && $data['tel'] = $tel;
        $second_cid && $data['second_cid'] = $second_cid;
        $data['admin_id'] = $userInfo['id'];
        $data['admin_name'] = $userInfo['name'];
        //客保设置
        $res = D('Resource/CommonSet','Service')->getCommonSetInfo(['id'=>1]);
        if(!$id){
            $data['status'] = 1;
            if(isset($res) && ($res['status']==1) && $res['data']){
                $arr = [];
                $field_all = explode(',',$res['data']);
                foreach ($field_all as $v){
                    $arr[$v] = $$v;
                }

                $customer_info = D('Resource/Customer','Service')->getCustomerInfo($arr);
                if($customer_info){
                    if(($customer_info['status']==0)){
                        $data['status']=0;
                        //return Response(2000,'该客户正在审核中');
                    }
                    if(($customer_info['status']==1) && ($customer_info['phase']!=20)){
                        $data['status']=0;
                        //return Response(2001,'该客户正在跟进中,无需重复录入');
                    }
                    if(in_array($customer_info['status'],[5,10])){
                        return Response(5000,'该客户已存在，当前可被申领');
                    }
                }
            }

            $result = D('Resource/Customer','Service')->addCustomer($data);
            if($result){
                $add_data = [];
                $add_data['customer_id'] = $result;
                $add_data['admin_id'] = $userInfo['id'];
                $add_data['description'] = '客户信息录入';
                D('Resource/PhaseLog','Service')->addPhaseLog($add_data);
            }

        }else{
            $data['id'] = $id;
            $result = D('Resource/Customer','Service')->updateCustomerInfo($data);
            if($result){
                $add_data = [];
                $add_data['customer_id'] = $id;
                $add_data['admin_id'] = $userInfo['id'];
                $add_data['description'] = '客户信息更新';
                D('Resource/PhaseLog','Service')->addPhaseLog($add_data);
            }
        }
        if(!$result){
            return Response(2009,"操作失败");
        }else{
            return Response(999,"操作成功");
        }
    }

    /**
     * 客户列表（业务员）
     * @param $params
     * @return mixed
     */
    public function searchCustomerList($params) {
        $result = D('Resource/Customer', 'Service')->searchCustomerList($params);
        if(is_array($result['dataList']) && count($result['dataList'])>0){
            foreach($result['dataList'] as $k=>$v){
                $item_cate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$v['cid']]);
                $second_cate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$v['second_cid']]);
                $result['dataList'][$k]['first_name'] = $item_cate['name'];
                $result['dataList'][$k]['second_name'] = $second_cate['name'];

                $data = [];
                $data['customer_id'] = $v['id'];
                $data['admin_id'] = $v['admin_id'];
                $data['status'] = ['gt',0];
                $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);

                if($orderInfo){
                    $result['dataList'][$k]['order_id'] = $orderInfo['id'];
                    $result['dataList'][$k]['order_status'] = $orderInfo['status'];
                }

            }
            $tr = new CustomerTransformer();
            $result['dataList'] = $tr->TransformerCollection($result['dataList']);
        }
        return $result;
    }

    /**
     * 客户信息（业务员）
     * @param $params
     * @return array
     */
    public function getCustomerInfo($params){
        $customerInfo = D('Resource/Customer','Service')->getCustomerInfo($params);
        if(is_array($customerInfo) && count($customerInfo)){
            $cateInfo = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$customerInfo['cid']]);
            $customerInfo['first_name'] = $cateInfo['name'];
            $second_cate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$customerInfo['second_cid']]);
            $customerInfo['second_name'] = $second_cate['name'];

            $tr = new CustomerTransformer();
            $customerInfo = $tr->Transformer($customerInfo);

            $data = [];
            $data['customer_id'] = $customerInfo['id'];
            $data['admin_id'] = $customerInfo['admin_id'];
            $data['status'] = ['neq',-1];
            $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);
            $customerInfo['is_order'] = 0;
            if($orderInfo && ($orderInfo['status']>25)){
                $customerInfo['is_order'] = 1;
            }

            if($orderInfo){
                $customerInfo['order_id'] = $orderInfo['id'];
                $customerInfo['order_status'] = $orderInfo['status'];
            }

        }
        return $customerInfo;
    }

    /**
     * 申领
     * @param $params
     * @return string
     */
    public function autoApplicantCustomer($params){
        $company_name = trim($params['company_name']);
        $product_name = trim($params['product_name']);
        $admin_id = intval($params['admin_id']);
        $cid = intval($params['cid']);

        $arr = [];
        $arr['company_name'] = $company_name;
        $arr['product_name'] = $product_name;
        $arr['cid'] = $cid;
        $result = '';
        $customer_info = D('Resource/Customer','Service')->getCustomerInfo($arr);
        if($customer_info){
            $orderInfo = D('Resource/Order')->getOneOrderInfo(['customer_id'=>$customer_info['id']]);
            if(($customer_info['status']==0)){
                return Response(2000,'该客户正在审核中');
            }
            if(($customer_info['status']==1) && ($customer_info['phase']!=20)){
                return Response(2001,'该客户正在跟进中,无需重复录入');
            }
            if(in_array($customer_info['status'],[5,10])){
                if(!$orderInfo){
                    $arr = [];
                    $arr['id'] = $customer_info['id'];
                    $arr['status'] = 1;
                    $arr['admin_id'] = $admin_id;
                    $arr['applicant_id'] = $admin_id;
                    $arr['old_id'] = $customer_info['admin_id'];
                    $result = D('Resource/Customer','Service')->updateCustomerInfo($arr);
                    unset($arr);
                }else{
                    if($orderInfo['status']<5){
                        $arr = [];
                        $arr['id'] = $customer_info['id'];
                        $arr['status'] = 1;
                        $arr['admin_id'] = $admin_id;
                        $arr['applicant_id'] = $admin_id;
                        $arr['old_id'] = $customer_info['admin_id'];
                        $result = D('Resource/Customer','Service')->updateCustomerInfo($arr);
                        unset($arr);
                    }else{
                        $arr = [];
                        $arr['id'] = $customer_info['id'];
                        $arr['status'] = 0;
                        $arr['admin_id'] = $admin_id;
                        $arr['applicant_id'] = $admin_id;
                        $arr['old_id'] = $customer_info['admin_id'];
                        $result = D('Resource/Customer','Service')->updateCustomerInfo($arr);
                        unset($arr);
                    }
                }
            }
            if(!$result){
                return Response(3000,"申领失败");
            }
            return Response(999,"申领成功");
        }
        return Response(3001,"未查询到该客户信息");
    }

    /**
     * 业支审核客户
     * @param $params
     * @return string
     */
    public function yzAuditingCustomer($params){
        $id = intval($params['id']);
        $status = intval($params['status']);
        $refuse_reason = trim($params['refuse_reason']);
        $type = trim($params['type']);

        $customer = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$id]);
        if(!$customer){
            return Response(2001,"未查询到该客户信息");
        }
        if(!in_array($customer['status'],[0,5])){
            return Response(2002,"该客户无需审核");
        }
        $data = [];
        $data['id'] = $id;
        $data['status'] = $status;
        if($type=='pass'){
            $arr['admin_id'] = $customer['applicant_id'];
        }
        $refuse_reason && $data['refuse_reason'] = $refuse_reason;
        //订单
        $orderInfo = D('Resource/Order')->getOneOrderInfo(['customer_id'=>$customer['id']]);

        $res = D('Resource/Customer','Service')->updateCustomerInfo($data);
        if(!$res){
            return Response(203,"网络请求失败");
        }else{
            $admin = D('Resource/User','Service')->getUserInfo(['id'=>$customer['applicant_id']]);
            if($orderInfo && $type=='pass'){
                $order = [];
                $order['id'] = $orderInfo['id'];
                $order['admin_id'] = $admin['id'];
                $order['admin_name'] = $admin['username'];
                $order['department_id'] = $admin['department_id'];
                D('Resource/Order','Service')->updateOrderInfo($order);
            }
            return Response(999,"请求成功");
        }
    }

    /**
     * 通用
     * @param $params
     * @return mixed
     */
    public function searchCommonCustomerList($params) {
        $result = D('Resource/Customer', 'Service')->searchCommonCustomerList($params);
        if(is_array($result['dataList']) && count($result['dataList'])>0){
            foreach($result['dataList'] as $k=>$v){
                $item_cate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$v['cid']]);
                $second_cate = D('Resource/ItemCate','Service')->getCateInfo(['id'=>$v['second_cid']]);
                $result['dataList'][$k]['first_name'] = $item_cate['name'];
                $result['dataList'][$k]['second_name'] = $second_cate['name'];
            }
            $tr = new CustomerTransformer();
            $result['dataList'] = $tr->TransformerCollection($result['dataList']);
        }
        return $result;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function getAdminCustomerCount($params){
        $admin_id = $params['admin_id'];
        $data = [];
        $data['admin_id'] = $admin_id;
        $data['phase'] = ['in',[1,5,10,15]];
        $data['status'] = 1;
        $result = D('Resource/Customer','Service')->getCustomerCount($data);
        return $result;
    }

    public function ajaxChangeCustomerOrder($params){
        $department_id = $params['department_id'];
        $admin_id = $params['admin_id'];
        $chooseList = $params['chooseList'];

        $userInfo = D('Resource/User','Service')->getUserInfo([
            'id'=>$admin_id,
            'department_id'=>$department_id
        ]);
        if(!$userInfo){
           return Response(2002,"未查询到该用户信息");
        }
        $err = 0;
        if(is_array($chooseList) && count($chooseList)>0){
            foreach ($chooseList as $key=>$item){
                $customerInfo = D('Resource/Customer','Service')->getCustomerInfo(['id'=>$item['id']]);
                if($customerInfo){
                    $data = [];
                    $data['customer_id'] = $customerInfo['id'];
                    $data['admin_id'] = $customerInfo['admin_id'];
                    $data['status'] = ['neq',-1];
                    $orderInfo = D('Resource/Order','Service')->getOrderInfo($data);
                    //bill
                    $data_b = [];
                    $data_b['customer_id'] = $customerInfo['id'];
                    $data_b['admin_id'] = $customerInfo['admin_id'];
                    $orderBill = D('Resource/OrderBill','Service')->getOrderBillInfo($data_b);


                    $model = new Model();
                    $model->startTrans();
                    $flag = false;
                    $c = D('Resource/Customer','Service')->updateCustomerInfo([
                        'id'=>$customerInfo['id'],
                        'phase'=>1,
                        'status'=>1,
                        'admin_id' => $userInfo['id'],
                        'admin_name' => $userInfo['name'],
                    ]);
                    if($c==false){
                        $flag = true;
                    }
                    if($orderInfo){
                        $o = D('Resource/Order','Service')->updateOrderInfo([
                            'id'=>$orderInfo['id'],
                            'admin_id' => $userInfo['id'],
                            'department_id' => $userInfo['department_id'],
                            'admin_name' => $userInfo['name'],
                        ]);
                        if($o==false){
                            $flag = true;
                        }
                    }
                    if($orderBill){
                        $b = D('Resource/OrderBill','Service')->updateOrderBillInfo([
                            'id'=>$orderBill['id'],
                            'admin_id' => $userInfo['id'],
                            'admin_name' => $userInfo['name'],
                            'customer_id' => $customerInfo['id'],
                        ]);
                        if($b==false){
                            $flag = true;
                        }
                    }
                    if(!$flag){
                        $model->commit();
                    }else{
                        $err++;
                        $model->rollback();
                    }
                }
            }
        }
        if($err>0){
           return Response(2003,"网络请求异常");
        }
        return Response(999,"网络请求成功");
    }
}